package com.example.firstdemo.ui.screens.pages.problem.problemDetail

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.calculateEndPadding
import androidx.compose.foundation.layout.calculateStartPadding
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.input.TextFieldLineLimits
import androidx.compose.foundation.text.input.rememberTextFieldState
import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBackIosNew
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import coil3.compose.SubcomposeAsyncImage
import com.example.firstdemo.Config
import com.example.firstdemo.R
import com.example.firstdemo.network.api.problem.data.ConfirmData
import com.example.firstdemo.ui.screens.components.Dialog
import com.example.firstdemo.ui.screens.components.TopAppBar
import com.example.firstdemo.ui.screens.pages.problem.problemDetail.data.LocalProblemDetailDataProvider
import com.example.firstdemo.ui.screens.pages.problem.problemDetail.data.ProblemDetailUIState
import com.example.firstdemo.ui.theme.AppTheme
import com.example.firstdemo.ui.theme.FontSize
import com.example.firstdemo.ui.theme.Space
import com.example.firstdemo.ui.theme.eColors

@Composable
fun ProblemDetail(
    padding: PaddingValues = PaddingValues(0.dp),
    uiState: ProblemDetailUIState,
    onBack: () -> Unit = {},
    onGetDetail: () -> Unit = {},
    onSetDialogShow: (show: Boolean) -> Unit = {},
    onConfirm: (data: ConfirmData) -> Unit = {}
) {
    val scrollState = rememberScrollState()
    val problem = uiState.problem
    val description = rememberTextFieldState("")
    LaunchedEffect(Unit) {
        onGetDetail()
    }

    Surface(
        Modifier
            .padding(
                PaddingValues(
                    start = padding.calculateStartPadding(LayoutDirection.Ltr),
                    top = 0.dp,
                    end = padding.calculateEndPadding(LayoutDirection.Ltr),
                    bottom = padding.calculateBottomPadding()
                )
            )
            .fillMaxSize()
    ) {
        Column {
            TopAppBar(
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(
                            imageVector = Icons.Filled.ArrowBackIosNew,
                            contentDescription = "Localized description"
                        )
                    }
                },
                actions = {
                    IconButton(onClick = {}) {}
                },
            ) {
                Text(
                    "故障详情",
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
            }

            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f)
                    .verticalScroll(scrollState)
            ) {
                Surface(shadowElevation = 1.dp) {
                    Column(Modifier.padding(Space.xl, Space.medium, Space.xl, Space.medium)) {
                        InfoItem("故障名称", problem?.remarks ?: "")
                        InfoItem("探测站", uiState.stationName)
                        InfoItem("过车时间", problem?.passTime ?: "")
                        InfoItem("车次", problem?.vehicleNumber ?: "")
                        InfoItem("辆序", problem?.carriageOrder)
                        InfoItem("车号", problem?.carriageNo ?: "")
                    }
                }
                Box(Modifier.padding(Space.medium, Space.medium, Space.medium, 0.dp)) {
                    Surface(
                        shape = MaterialTheme.shapes.medium,
                        border = BorderStroke(1.dp, MaterialTheme.eColors.border.base)
                    ) {
//                        ZoomableImage("https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg")
                        SubcomposeAsyncImage(
                            model = "${Config.BASE_URL}${problem?.imgPath?.removePrefix("/")}",
//                            model = "https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg",
//                            loading = {
//                                CircularProgressIndicator()
//                            },
                            error = {
                                Box(
                                    contentAlignment = Alignment.Center,
                                    modifier = Modifier
                                        .height(150.dp)
                                ) {
                                    Image(
                                        painter = painterResource(R.drawable.img_error),
                                        null,
                                        contentScale = ContentScale.Crop,
                                        modifier = Modifier.size(60.dp)
                                    )
                                }
                            },
                            contentDescription = null,
                            modifier = Modifier.fillMaxSize(),
                            contentScale = ContentScale.FillWidth
                        )
                    }
                }
                Box(Modifier.padding(Space.medium, Space.medium, Space.medium, 0.dp)) {
                    Column {
                        TextField(
                            shape = MaterialTheme.shapes.medium,
                            colors = TextFieldDefaults.colors(
                                unfocusedContainerColor = MaterialTheme.eColors.background.base,
                                focusedIndicatorColor = Color.Transparent,
                                unfocusedIndicatorColor = Color.Transparent
                            ),
                            state = description,
                            lineLimits = TextFieldLineLimits.MultiLine(
                                minHeightInLines = 3,
                                maxHeightInLines = 6
                            ),
                            placeholder = {
                                Text(
                                    text = "故障描述",
                                    fontSize = FontSize.medium,
                                    color = MaterialTheme.eColors.text.placeholder
                                )
                            },
                            textStyle = TextStyle(color = MaterialTheme.eColors.text.regular),
                            modifier = Modifier.fillMaxWidth()
                        )
                        Spacer(Modifier.height(Space.small))
                        Row {
                            QuickBox(
                                "属实", Modifier.clickable(
                                    onClick = {
                                        description.setTextAndPlaceCursorAtEnd("属实")
                                    }
                                ))
                            Spacer(Modifier.width(Space.xs))
                            QuickBox(
                                "不属实", Modifier.clickable(
                                    onClick = {
                                        description.setTextAndPlaceCursorAtEnd("不属实")
                                    }
                                ))
                        }
                    }
                }
                Box(Modifier.padding(Space.medium, Space.medium, Space.medium, 0.dp)) {
                    Button(
                        shape = MaterialTheme.shapes.medium,
                        onClick = {
                            onSetDialogShow(true)
                        },
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(40.dp)
                    ) {
                        Text(
                            text = "故障确认",
                            color = MaterialTheme.eColors.basic.white
                        )
                    }
                }
            }
        }
    }
    if (uiState.dialogShow) {
        Dialog(
            title = "提示",
            info = "确认提交？",
            onConfirm = {
                onSetDialogShow(false)
                onConfirm(
                    ConfirmData(
                        passTime = problem?.passTime ?: "",
                        uid = problem?.uid ?: "",
                        confirmSuggestion = description.text.toString()
                    )
                )
            },
            onDismiss = {
                onSetDialogShow(false)
            }
        )
    }
}


@Composable
fun QuickBox(text: String, modifier: Modifier = Modifier) {
    Surface(
        shape = MaterialTheme.shapes.small,
        border = BorderStroke(1.dp, MaterialTheme.eColors.border.base),
        color = MaterialTheme.eColors.background.base,
        modifier = modifier
    ) {
        Box(Modifier.padding(10.dp, 2.dp, 10.dp, 2.dp)) {
            Text(
                text = text,
                fontSize = FontSize.small
            )
        }
    }
}

@Composable
fun InfoItem(label: String, value: Int?) {
    InfoItem(label = label, value = if (value === null) "" else value.toString())
}

@Composable
fun InfoItem(label: String, value: String) {
    val labelWidth = 100.dp
    Row {
        Box(Modifier.width(labelWidth)) {
            Text(
                text = label,
                fontSize = FontSize.medium,
                color = MaterialTheme.eColors.text.secondary
            )
        }
        Box(Modifier.weight(1f)) {
            Text(
                text = value,
                fontSize = FontSize.medium,
                color = MaterialTheme.eColors.text.regular
            )
        }
    }
}

@Preview(
    showSystemUi = true
)
@Composable
fun ProblemDetailPreview() {
    AppTheme {
        ProblemDetail(
            padding = PaddingValues(top = 30.dp),
            uiState = LocalProblemDetailDataProvider.problemDetailUIState
        )
    }
}

